const targetMap = new WeakMap();
let activeEffect = null // 副作用函数

export function effect(fn, options = {}) {
    const effectFn = () => {
        try {
            activeEffect = fn
            return fn()
        } catch (error) {
            console.log(error);
        }
    }
    effectFn()
}

//依赖收集
export function track(target, type, key) {
    let depsMap = targetMap.get(target);
    if (!depsMap) {
        targetMap.set(target, depsMap = new Map());
    }
    let deps = depsMap.get(key);
    if (!deps) {
        deps = new Set()
    }
    if (!deps.has(activeEffect) && activeEffect) {
        deps.add(activeEffect)
    }
    depsMap.set(key, deps)
}

//触发依赖

export function trigger(target, type, key) {
    const depsMap = targetMap.get(target); //depsMap是某一个map对象
    if (!depsMap) return

    const deps = depsMap.get(key) //deps是一个Set
    if (!deps) return

    deps.forEach(effect => {
        effect()
    })

}